import java.io.PrintWriter;
import java.io.FileNotFoundException;

/**
 * Created by IntelliJ IDEA.
 * User: Rajeev
 * Date: Dec 29, 2009
 * Time: 2:57:49 PM
 * To change this template use File | Settings | File Templates.
 */
public class PrettyPrinter {
    String tab = "    ";
    PrintWriter pw = null;

    public void print(Node syntaxTree, String outFile) throws FileNotFoundException {
        this.pw = new PrintWriter(outFile);
        System.out.println("pretty printer output:");
        recursivePrint(syntaxTree, 0);
        pw.flush();
        pw.close();
    }

    // todo - test for bugs & improve quality.
    private void recursivePrint(Node current, int level) {
       StringBuilder sb = new StringBuilder("");
        for (int i=0; i< level; i++) {
            sb.append(tab);
        }
        if (current.children.size() > 0) {
             sb.append("+");                // expanded.
        }  else if (current.inline) {
            sb.append("-");               // no children at all.....
        }  else {
            sb.append("*");
        }
        sb.append(current.type);

        int size = 0;
        if ((size = current.attributes.size()) > 0 ) {
            sb.append("   [");
            int i = 0;
            for (Attribute a: current.attributes) {
                sb.append(a.type);
                sb.append(": ");
                sb.append(a.value);
                i++;
                if (i < size) {
                    sb.append(", ");
                }
            }
            sb.append("]");
        }

        pw.println(sb.toString());
        System.out.println(sb.toString());
        for (Node child: current.children) {
            recursivePrint(child, level+1);
        }
    }
}
